package com.ycode.bang.anbang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.baseui.BaseActivity;
import com.ycode.bang.anbang.model.LoginModel;
import com.ycode.bang.anbang.network.FinalHttpUtil;
import com.ycode.bang.anbang.utils.DialogProgress;
import com.ycode.bang.anbang.utils.RequestMapDev;
import com.ycode.bang.anbang.utils.StringUtils;
import com.ycode.bang.anbang.utils.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by maosongsong on 2016/4/5.
 */
public class LoginActivity2 extends BaseActivity implements View.OnClickListener, TextWatcher {
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.et_username)
    EditText mEtUsername;
    @InjectView(R.id.et_password)
    EditText mEtPassword;
    @InjectView(R.id.btn_login)
    Button mBtnLogin;
    @InjectView(R.id.btn_find_pass)
    Button mBtnFind;


    @InjectView(R.id.vb_remember)
    CheckBox checkBox;//记住密码勾选框

    SharedPreferences.Editor nameAndPass;
    SharedPreferences getName;

    public static final String RealName = "小区管理员";//角色管理
    DialogProgress mDialogProgress = new DialogProgress(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!MyApp.instance.isTokenEmpty()){
            finish();
        }
        addOurView(R.layout.activity_login2);
        ButterKnife.inject(this);
        initView();
        initData();
        editChange();
    }

    @Override
    protected void getSuccessRequest(Object response, int flag) {

    }

    public void initView() {
        back.setVisibility(View.GONE);
        title.setText("登录");
        mEtUsername.setOnClickListener(this);
        mEtPassword.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        mBtnFind.setOnClickListener(this);
        checkBox.setOnClickListener(this);
    }

    public void initData() {
        getName = getSharedPreferences("data", MODE_PRIVATE);
        if (!TextUtils.isEmpty(getName.getString("name", ""))) {
            mEtUsername.setText(getName.getString("name", ""));
        }
        if (!TextUtils.isEmpty(getName.getString("password", ""))) {
            mEtPassword.setText(getName.getString("password", ""));
        }
        if (getName.getString("ischeck", "").equals("1")){
            checkBox.setChecked(true);
        }else {
            checkBox.setChecked(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if (TextUtils.isEmpty(mEtUsername.getText().toString().trim())) {
                    ToastUtil.show(this, "请输入用户名！");
                    return;
                } else if (TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
                    ToastUtil.show(this, "请输入密码！");
                    return;
                } else {
                    login(mEtUsername.getText().toString().trim(), mEtPassword.getText().toString().trim());
//                    Intent intent = new Intent(this, HomepageActivity.class);
//                    startActivity(intent);
                }
                break;
            case R.id.vb_remember:
                if (checkBox.isChecked()) {
                    if (!TextUtils.isEmpty(mEtUsername.getText().toString().trim())) {
                        nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//存储用户名和密码
                        nameAndPass.putString("name", mEtUsername.getText().toString().trim());
                        nameAndPass.commit();
                    }
                    if (!TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
                        nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//存储用户名和密码
                        nameAndPass.putString("password", mEtPassword.getText().toString().trim());
                        nameAndPass.commit();
                    }
                    nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//是否选中
                    nameAndPass.putString("ischeck", "1");
                    nameAndPass.commit();
                } else {
                    if (nameAndPass != null) {
                        nameAndPass.clear();
                        nameAndPass.commit();
                    }
                    if (getName != null) {
                        SharedPreferences.Editor editor = getName.edit();
                        editor.clear();
                        editor.commit();
                    }
                    if (!TextUtils.isEmpty(mEtUsername.getText().toString().trim())) {
                        nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//存储用户名和密码
                        nameAndPass.putString("name", mEtUsername.getText().toString().trim());
                        nameAndPass.commit();
                    }
                    nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//是否选中
                    nameAndPass.putString("ischeck", "0");
                    nameAndPass.commit();
                }
                break;
            case R.id.btn_find_pass:
                Intent intent2 = new Intent(this, FindPasswordActivity.class);
                startActivity(intent2);
                break;
        }
    }

    /**
     * 监听用户名和密码的输入，为记住密码这个服务
     */
    public void editChange() {
        mEtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkBox.isChecked()) {
                    nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//存储用户名和密码
                    nameAndPass.putString("name", mEtUsername.getText().toString().trim());
                    nameAndPass.commit();
                } else {
                    if (nameAndPass != null) {
                        nameAndPass.clear();
                        nameAndPass.commit();
                    }

                }
            }
        });

        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkBox.isChecked()) {
                    nameAndPass = getSharedPreferences("data", MODE_PRIVATE).edit();//存储用户名和密码
                    nameAndPass.putString("password", mEtPassword.getText().toString().trim());
                    nameAndPass.commit();
                } else {
                    if (nameAndPass != null) {
                        nameAndPass.clear();
                        nameAndPass.commit();
                    }
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 登录
     */
    private void login(final String name, String password) {
        AjaxParams mAjaxParam = new AjaxParams();
//        mAjaxParam.put("csrfToken", MyApp.instance.getToken());
        mAjaxParam.put("j_username", name);
        mAjaxParam.put("j_password", password);
//        mAjaxParam.put("http.protocol.allow-circular-redirects", "true");
        DefaultHttpClient client = (DefaultHttpClient) FinalHttpUtil.finalHttp.getHttpClient();
        client.getParams().setParameter("http.protocol.allow-circular-redirects", true);
//        client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        mDialogProgress.showlistviewdialog("登录中……");
        FinalHttpUtil.post(RequestMapDev.Login, mAjaxParam, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                //放置数据
                mDialogProgress.closedialog();
                try {
                    JSONObject jsonObject = new JSONObject(o.toString());
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("message");
                    String data = jsonObject.getString("data");
                    if (status.equals("0")) {
                        Log.e("这个接口是成功的", o);
                        Gson gson = new Gson();
                        LoginModel loginModel = gson.fromJson(data, LoginModel.class);
                        MyApp.instance.setToken(loginModel.getCsrfToken());//放置token值
                        MyApp.instance.setUserType(loginModel.getRoles() + "");//放置登录角色
                        //     MyApp.instance.setUserType(loginModel.getRealName());//放置登录角色
                        ToastUtil.show(LoginActivity2.this, "登录成功");
                        Intent intent = new Intent(LoginActivity2.this, HomepageActivity.class);
                        startActivity(intent);
                        MyApp.userNumber=name;
                        finish();
                    } else {
                        ToastUtil.show(LoginActivity2.this, msg.toString());
                    }
                } catch (Exception e) {
                    ToastUtil.show(LoginActivity2.this, e.toString());
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                loginout_550(errorNo);
                mDialogProgress.closedialog();
//                ToastUtil.show(LoginActivity2.this, "登录失败原因----->" + t.toString() + "----" + strMsg);
            }
        });
    }
}
